package com.example.gybicycle.controller.common;


import com.example.gybicycle.common.entity.Result;

import com.example.gybicycle.common.util.DataUtil;
import com.example.gybicycle.common.util.ImageUtil;
import com.example.gybicycle.common.redis.RedisUtil;

import com.example.gybicycle.common.util.LoginUtil;
import com.example.gybicycle.dao.IndexDao;
import com.example.gybicycle.entity.Bike;
import com.example.gybicycle.entity.LoginInfo;
import com.example.gybicycle.entity.SysFile;
import com.example.gybicycle.entity.SysUser;
import com.example.gybicycle.entity.index.Index;
import com.example.gybicycle.service.BikeService;
import com.example.gybicycle.service.FileService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@Tag(name = "上传文件")
public class FileController {


    @Autowired
    private FileService fileService;

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private BikeService bikeService;
    @Autowired
    private IndexDao indexDao;

    @PostMapping("/mulupload")
    public Result mulupload(@RequestParam("file") MultipartFile[] files,@RequestParam("lat") String lat, HttpServletRequest request) {
        Integer num=(Integer) redisUtil.get("imgnumber");
        if(num==null)
            num=1;
        List<SysFile> filelist=new ArrayList<>();
        try {
            for(MultipartFile file:files){
                String fileName =  DataUtil.setFileName(file.getOriginalFilename(),num);
                String path=fileService.path+"/" + fileName;
                file.transferTo(new File(path));
                ImageUtil.compressImage(path,100);
                ImageUtil.shuiyin(path,lat);
                SysFile sysFile=new SysFile();
                sysFile.setName(fileName);
                sysFile.setUrl(fileService.urlHead+"/"+fileName);
                filelist.add(sysFile);
                num++;
            }
            redisUtil.set("imgnumber",num,DataUtil.toTomorrowScond());
            return Result.success(filelist);
        } catch(IOException e) {
            e.printStackTrace();
            return Result.fail("上传失败");
        }
    }
    @PostMapping("/upload")
    @Operation(summary =  "上传")
    public Result uploadsy(@RequestPart("file") MultipartFile file, @RequestPart(name = "lat",required = false) String lat, HttpServletRequest request) {
        Integer num=(Integer) redisUtil.get("imgnumber");
        if(num==null)
            num=1;
        try {
            String fileName =  DataUtil.setFileName(file.getOriginalFilename(),num);
            String path=fileService.path+"/" + fileName;
            file.transferTo(new File(path));
            ImageUtil.compressImage(path,100);
//            ImageUtil.shuiyin(path,lat);
            SysFile sysFile=new SysFile();
            sysFile.setName(fileName);
            sysFile.setUrl(fileService.urlHead+"/"+fileName);
            num++;
            redisUtil.set("imgnumber",num,DataUtil.toTomorrowScond());
            return Result.success(sysFile);
        } catch(IOException e) {
            e.printStackTrace();
            return Result.fail("上传失败");
        }
    }
    @PostMapping("/uploadProto")
    @Operation(summary =  "上传")
    public Result uploadFile(@RequestPart("file") MultipartFile file, HttpServletRequest request) {
        Integer num=(Integer) redisUtil.get("imgnumber");
        if(num==null)
            num=1;
        try {
            String fileName =  DataUtil.setFileName(file.getOriginalFilename(),num);
            String path=fileService.path+"/" + fileName;
            file.transferTo(new File(path));
            ImageUtil.compressImage(path,100);
            SysFile sysFile=new SysFile();
            sysFile.setName(fileName);
            sysFile.setUrl(fileService.urlHead+"/"+fileName);
            num++;
            redisUtil.set("imgnumber",num,DataUtil.toTomorrowScond());
            return Result.success(sysFile);
        } catch(IOException e) {
            e.printStackTrace();
            return Result.fail("上传失败");
        }
    }
    @PostMapping("/uploadroate")
    @Operation(summary =  "上传并旋转+水印")
    public Result uploadRotate(@RequestParam("file") MultipartFile file,@RequestParam(name = "lat",required = false) String lat,HttpServletRequest request) {
        Integer num=(Integer) redisUtil.get("imgnumber");
        if(num==null)
            num=1;
        try {
            String fileName =  DataUtil.setFileName(file.getOriginalFilename(),num);
            String path=fileService.path+"/" + fileName;
            file.transferTo(new File(path));
            ImageUtil.rotate(path);
            ImageUtil.compressImage(path,100);
            ImageUtil.shuiyin(path,lat);
            SysFile sysFile=new SysFile();
            sysFile.setName(fileName);
            sysFile.setUrl(fileService.urlHead+"/"+fileName);
            num++;
            redisUtil.set("imgnumber",num,DataUtil.toTomorrowScond());
            return Result.success(sysFile);
        } catch(IOException e) {
            e.printStackTrace();
            return Result.fail("上传失败");
        }
    }

    @PostMapping("/test")
    @Operation(summary = "單車-批量设置二维码")
    public Result te(){
//        String qrcode=fileService.createBikeQRCode(entity);
//        entity.setQrcode(qrcode);
        List<Bike> list=bikeService.findList(new Bike());
        for(Bike bike:list){
            String qrcode=fileService.createBikeQRCode(bike);
            bike.setQrcode(qrcode);
        }
        bikeService.updateByList(list);
        return Result.success(list);
    }
    @PostMapping("/testIndex")
    @Operation(summary = "首页测试")
    public Result<Index> testIndex(){
        Index index=new Index();
        index.setIncome(indexDao.findRevenueCount());
        index.setDayByCycling(indexDao.findCycleNum(1));
        index.setDayByCycle(indexDao.findCycleStateCount());
        index.setDayByIncome(indexDao.findCycleMoney(1));
        index.setFailurelist(indexDao.findFailure());
        index.setFailureHandle(indexDao.findFailureHandle());
        index.setCyclingMaps(indexDao.findCyclingMap());
        return Result.success(index);
    }

    @GetMapping(value = "/download",produces = "application/octet-stream")
    @Operation(summary =  "下载-二維碼")
//    @ApiImplicitParam(paramType = "query",name = "startTime", value = "时间[yyyy-MM-dd HH:mm:ss]", dataType = "Date",defaultValue = "2019-03-14 14:00:00")
    public void download(Bike bike, HttpServletRequest request, HttpServletResponse response) throws IOException {
//        LoginInfo info= LoginUtil.getLoginInfo(request);
//        if(info==null)
//            return  ;
        if(bike==null)
            bike=new Bike();
        var paths=bikeService.findCode(bike);
        String zip=fileService.downLoadBikeQRCode(paths);
        File file=new File(zip);
        // 设置响应头信息
        String filename = file.getName();
        // 文件转成字节数组
        byte[] fileByte = Files.readAllBytes(file.toPath());
        // 设置response的Header
        response.setCharacterEncoding("UTF-8");
        // 指定下载文件名(attachment-以下载方式保存到本地，inline-在线预览)
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
        // 告知浏览器文件的大小
        response.addHeader("Content-Length", "" + file.length());
        // 内容类型为通用类型，表示二进制数据流
        response.setContentType("application/octet-stream");
        OutputStream os = response.getOutputStream();
        os.write(fileByte);
        os.flush();
    }




}
